package com.kaibes.imserver.control.threads;

import java.io.IOException;

import com.kaibes.imserver.KaibesIMServer;
import com.kaibes.imserver.control.MainClientControl;
import com.kaibes.imserver.control.UserSocketControl;
import com.kaibes.imserver.view.ServerMainView;

public class ServerSocketAccept implements Runnable {

	private MainClientControl socketControl;

	public ServerSocketAccept() {
		this.socketControl = KaibesIMServer.mainClientControl;
	}

	@Override
	public void run() {
		boolean flag = true;
		while (flag) {
			UserSocketControl userSocketControl;
			try {
				userSocketControl = new UserSocketControl(socketControl.getServerSocket().accept());
				KaibesIMServer.mainClientControl.putLoginSocketControl(userSocketControl.getClient().getRemoteSocketAddress().toString(), userSocketControl);

				if (socketControl.isFullConnect()) {
					ServerMainView.serverPanelView.panel_start
							.addLog(this
									+ ": the server has a maximum number of connections."
									+ socketControl.getServerConnectMax());
				} else {
					socketControl.addServerConnect();
					String ipAddress = userSocketControl.getClient().getInetAddress().toString();

					if (socketControl.isFullIpConnect(ipAddress)) {
						ServerMainView.serverPanelView.panel_login
								.addLog(this
										+ ": "
										+ ipAddress
										+ " try to connect, but it has too many connections!");
						socketControl.removeServerConnect();

					} else {
						socketControl.addIpconnect(ipAddress);
						ServerMainView.serverPanelView.panel_login.addLog(this
								+ ": " + ipAddress
								+ " connect!");
						
						//给每个socket开启登陆监听线程，会在登陆成功后死亡，可以开启多个，但是没必要浪费资源
						userSocketControl.createThreadLogin(1);
					}
				}
				
				System.err.println("死循环警告！");

			} catch (IOException e) {
				flag = false;
				// e.printStackTrace();
			}

		}

	}

}
